import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/apis/user_api.dart';
import 'package:sainbainu/common/repositories/user_repository.dart';
import 'package:sainbainu/common/services/user.dart';
import 'package:sainbainu/common/utils/loading.dart';
import 'package:sainbainu/common/values/sizes.dart';

import 'index.dart';

/// 头部额外高度（不含appbar）
const double kHeaderExtarHeight = 390.0;

class UserDetailController extends GetxController
    with GetSingleTickerProviderStateMixin {
  UserDetailController();

  final state = UserDetailState();

  @override
  void onInit() {
    super.onInit();

    if (Get.arguments == null || Get.arguments['customerId'] == null) {
      handleBack();
      return;
    }

    state.tabController = TabController(length: 3, vsync: this);
    state.scrollController = ScrollController();
    state.scrollController.addListener(() {
      calcCollapsed();
      calcTitleOpacity();
    });
    state.userRepository = UserRepository(UserApi());

    state.customerId = Get.arguments['customerId'] as int;
    state.isMe =
        UserService.to.accountInfo.value.customerId == state.customerId;

    getUserDetail();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
    state.scrollController.dispose();
    state.tabController.dispose();
  }

  /// 计算上滑头部完全折叠
  calcCollapsed() {
    bool isCollapsed = state.scrollController.offset >=
        kProfileCoverHeight - kProfileTabbarHeight - kToolbarHeight;
    if (state.isCollapsed.value != isCollapsed) {
      state.isCollapsed.value = isCollapsed;
    }
  }

  /// 完全展开到开始渐变时的高度
  calcTitleOpacity() {
    double collapsedHeight = kProfileCoverHeight -
        kToolbarHeight -
        kToolbarHeight -
        kProfileTabbarHeight;

    if (state.scrollController.offset >= collapsedHeight) {
      // 计算上滑标题透明度
      double opacity = min(
        (state.scrollController.offset - collapsedHeight) / kToolbarHeight,
        1,
      );
      if (state.titleOpacity.value != opacity) {
        state.titleOpacity.value = opacity;
      }
    } else {
      if (state.titleOpacity.value != 0.0) {
        state.titleOpacity.value = 0.0;
      }
    }
  }

  /// 详情
  Future<void> getUserDetail() async {
    var userDetail =
        await state.userRepository.otherUserInfo(state.customerId!);

    state.otherUserInfo = userDetail;
    update(['userDetail']);
  }

  /// 关注、取消关注
  void onFollowHandle() {
    if (state.otherUserInfo.followFlag == 1) {
      state.userRepository.unFollow(state.customerId!);
      state.otherUserInfo.followFlag = 0;
    } else {
      state.userRepository.follow(state.customerId!);
      state.otherUserInfo.followFlag = 1;
    }
    update(['btn']);
  }

  /// 返回
  void handleBack() {
    Get.back();
  }

  toFollowPage() {}

  toFansPage() {}
}
